import {Component, ElementRef, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {AppService} from '../../../app.service';
import {FileManagementService} from '../file-management.service';
import {NzMessageService} from 'ng-zorro-antd';
import {CommonTool} from '../../../common/common.tool';

@Component({
  selector: 'app-create-folder',
  templateUrl: './create-folder.component.html',
  styleUrls: ['./create-folder.component.scss']
})
export class CreateFolderComponent implements OnInit {
  /**
   * 创建目录
   */
  public createFolder = {
    isVisible: false,
    folderId: '',
    name: '',
    okDisabled: true,
    nameStatus: ''
  };
  @Output()
  public createSuccess: EventEmitter<any> = new EventEmitter<any>();
  @ViewChild('createFolderName', {static: true})
  public createFolderName: ElementRef;

  constructor(public appService: AppService,
              private message: NzMessageService,
              public fileManagementService: FileManagementService) {
  }

  ngOnInit() {
  }

  /**
   * 确认创建弹窗
   */
  public createFolderOk() {
    this.appService.setLoading(true);
    const req = {
      name: this.createFolder.name
    };
    this.fileManagementService.createFolder(this.createFolder.folderId, req).subscribe(res => {
      this.appService.setLoading(false);
      this.createFolder.name = '';
      this.createFolder.isVisible = false;
      this.message.success('创建成功！');
      this.createSuccess.emit(res);
    });
  }

  /**
   * 打开模板
   */
  public modalOpen(key) {
    this[key].nativeElement.focus();
  }

  /**
   * 验证文件目录输入框
   */
  public folderInput(data, field) {
    if (!CommonTool.notNull(data[field])) {
      data[field + 'Status'] = 'error';
      data.okDisabled = true;
      return;
    }
    const pattern = new RegExp('[/\\\\:*?"<>|]');
    if (pattern.test(data[field])) {
      data[field + 'Status'] = 'error';
      data.okDisabled = true;
    } else {
      data.okDisabled = false;
      data[field + 'Status'] = '';
    }
  }

  /**
   * 创建
   */
  public create(folderId) {
    this.createFolder = {
      isVisible: true,
      folderId,
      name: '',
      okDisabled: true,
      nameStatus: ''
    };
  }
}
